package com.yeyks.service.impl;

import com.yeyks.dal.dao.SignInMapper;
import com.yeyks.dal.domain.FishBall;
import com.yeyks.dal.domain.FishBallBill;
import com.yeyks.dal.domain.SignIn;
import com.yeyks.dto.SignInDTO;
import com.yeyks.exception.ServiceException;
import com.yeyks.model.enums.FishBallEnum;
import com.yeyks.service.FishBallService;
import com.yeyks.service.SignInService;
import com.yeyks.util.DateUtils;
import com.yeyks.util.ObjectConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author fuchangshuai
 * @date 2019/4/24 0024
 */
@Service
@Slf4j
public class SignInServiceImpl implements SignInService {

    @Autowired
    private SignInMapper signInMapper;
    @Autowired
    private FishBallService fishBallService;


    /**
     * 签到
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Map<String, Integer> signIn(Integer userId) {
        Map<String, Integer> map = new HashMap<>();
        try {
            SignIn signIn = signInMapper.selectSignByUserId(userId);
            if (signIn == null) {
                SignIn newSignIn = createSignAndSave(userId, null);
                fishBallService.addFishBall(newSignIn.getFishBallCount(), userId, 1, FishBallEnum.SIGN.desc());
                map.put("remainAmount", newSignIn.getFishBallCount());
                map.put("count", newSignIn.getFishBallCount());
                return map;
            }
            if (signIn.getSignTime() == null) {
                signIn.setSignTime(new Date());
            }
            Date signTime = signIn.getSignTime();
            Date nowBeginDate = DateUtils.dayBegin(0);
            if (DateUtils.dateCompareDate(signTime, nowBeginDate)) {
                throw new ServiceException("您已经签到过");
            }
            //判断是否是连续签到
            if (!sign(signTime, nowBeginDate)) {
                //非连续签到
                signIn.setContinueDays(0);
            }
            SignIn newSignIn = createSignAndSave(userId, signIn.getContinueDays());
            Integer remainAmount = fishBallService.addFishBall(newSignIn.getFishBallCount(), userId, 1, FishBallEnum.SIGN.desc());
            map.put("remainAmount", remainAmount);
            map.put("count", newSignIn.getFishBallCount());
            return map;
        } catch (ServiceException e) {
            throw new ServiceException("您已经签到过");
        } catch (Exception e) {
            log.error("签到异常{}", e.getLocalizedMessage());
            e.printStackTrace();
            map.put("remainAmount", 0);
            map.put("count", 0);
        }
        return map;
    }

    /**
     * 是否已经签到过
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean isSign(Integer userId) {
        SignIn signIn = signInMapper.selectSignByUserId(userId);
        Date signTime = signIn.getSignTime();
        Date nowBeginDate = DateUtils.dayBegin(0);
        return DateUtils.dateCompareDate(signTime, nowBeginDate);
    }

    /**
     * 获取用户签到信息
     *
     * @param userId
     * @return
     */
    @Override
    public SignInDTO info(Integer userId) {
        SignInDTO signInDTO = new SignInDTO();
        SignIn signIn = signInMapper.selectSignByUserId(userId);
        if (signIn != null) {
            signInDTO.setContinueDays(signIn.getContinueDays());
            signInDTO.setSignTime(signIn.getSignTime());
            signInDTO.setUserId(signIn.getUserId());
            Date signTime = signIn.getSignTime();
            Date nowBeginDate = DateUtils.dayBegin(0);
            if (DateUtils.dateCompareDate(signTime, nowBeginDate)) {
                signInDTO.setIsSign(true);
            } else {
                signInDTO.setIsSign(false);
            }
        } else {
            signInDTO.setIsSign(false);
            signInDTO.setContinueDays(0);
            signInDTO.setSignTime(null);
            signInDTO.setUserId(userId);
        }

        FishBall fishBall = fishBallService.getFishBallNoCreate(userId);
        int totalAmount = fishBall.getTotalAmount() == null ? 0 : fishBall.getTotalAmount();
        int useAmount = fishBall.getUseAmount() == null ? 0 : fishBall.getUseAmount();
        int remainAmount = totalAmount - useAmount < 0 ? 0 : totalAmount - useAmount;
        signInDTO.setTotalAmount(totalAmount);
        signInDTO.setRemainAmount(remainAmount);
        return signInDTO;
    }

    private boolean sign(Date signTime, Date nowBeginDate) {
        //获取当前时间前一天的时间
        Date afterDay = DateUtils.afterDaysToDate(nowBeginDate, -1L);
        Date newSignTime = DateUtils.dayBegin(signTime, 0);
        //连续签到
        return afterDay.compareTo(newSignTime) == 0;
    }

    private SignIn createSignAndSave(Integer userId, Integer continueDays) {
        SignIn signIn = new SignIn();
        int randomSign = getRandomSign() * 5;
        signIn.setUserId(userId);
        if (continueDays == null) {
            signIn.setContinueDays(1);
        } else {
            signIn.setContinueDays(continueDays + 1);
        }
        signIn.setSignTime(new Date());
        signIn.setFishBallCount(randomSign);
        int res = signInMapper.insert(signIn);
        if (res == 1) {
            return signIn;
        } else {
            signIn.setFishBallCount(0);
            return signIn;
        }
    }

    private int getRandomSign() {
        Random random = new Random();
        return random.nextInt(5) + 1;
    }


}
